<?php
/**
 * @copyright   2008-2014 简好网络 <http://www.phpshe.com>
 * @creatdate   2012-0501 koyshe <koyshe@gmail.com>
 */
pe_lead('hook/wechat.hook.php');
$xml = wechat_getxml();
$shop_name = $xml['ToUserName'];
$user_wx_openid = $xml['FromUserName'];
switch ($xml['MsgType']) {
	//####################// 事件推送 //####################//
	case 'event':
		if (in_array($xml['Event'], array('subscribe', 'unsubscribe'))) {
			$user = $db->pe_select('user', array('shop_id'=>$shop['shop_id'], 'user_wx_openid'=>$user_wx_openid));
			if ($xml['Event'] == 'subscribe') {
				user_follow_callback($user, 1);
				$info = $db->pe_select('wechat_follow', array('shop_id'=>$shop['shop_id']));
				if (!$info['follow_state']) die();
				$xml_arr['ToUserName'] = $user_wx_openid;
				$xml_arr['FromUserName'] = $shop_name;
				$xml_arr['CreateTime'] = time();
				$xml_arr['MsgType'] = 'text';
				$xml_arr['Content'] = $info['follow_reply'];
				echo wechat_sendxml($xml_arr);
			}
			else {
				user_follow_callback($user, 0);					
			}
		}
		elseif ($xml['Event'] == 'CLICK') {
			$shopinfo = $db->pe_select('shopinfo', array('shop_id'=>$shop['shop_id']));
			$menu_list = $shopinfo['wechat_menu'] ? unserialize($shopinfo['wechat_menu']) : array();
			foreach($menu_list as $v) {
				if ($v['key'] == $xml['EventKey']) {
					$follow_reply = $v['text'];
					break;
				}
				if (is_array($v['list'])) {
					foreach ($v['list'] as $vv) {
						if ($vv['key'] == $xml['EventKey']) {
							$follow_reply = $vv['text'];
							break;
						}
					}
				}
			}
			if ($follow_reply) {
				$xml_arr['ToUserName'] = $user_wx_openid;
				$xml_arr['FromUserName'] = $shop_name;
				$xml_arr['CreateTime'] = time();
				$xml_arr['MsgType'] = 'text';
				$xml_arr['Content'] = $follow_reply;
				echo wechat_sendxml($xml_arr);				
			}
		}
	break;
	//####################// 关键词回复 //####################//
	case 'text':
		//file_put_contents("{$pe['path']}1.txt", $xml['Content']);
		if ($xml['Content']) {
			$info = $db->pe_select('wechat_keyword', array('shop_id'=>$shop['shop_id'], 'keyword_word'=>pe_dbhold($xml['Content'])));
			if (!$info['keyword_state']) die();
			$xml_arr['Content'] = $info['keyword_reply'];
			$xml_arr['ToUserName'] = $user_wx_openid;
			$xml_arr['FromUserName'] = $shop_name;
			$xml_arr['CreateTime'] = time();
			$xml_arr['MsgType'] = 'text';
			echo wechat_sendxml($xml_arr);
		}
	break;
	default:
		wechat_bind();
	break;
}
?>